<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head th:replace="~{fragments/layout :: head('OpenFeign测试')}"></head>
<body>
    <!-- 导航栏 -->
    <nav th:replace="~{fragments/layout :: navbar}"></nav>
    
    <!-- 页面内容 -->
    <div th:replace="~{fragments/layout :: content(~{::main})}">
        <main>
            <!-- 标题 -->
            <div class="container mt-4">
                <h1 class="mb-4">OpenFeign服务调用测试</h1>
                <p class="lead">本页面用于测试OpenFeign微服务调用功能，包括查询存在和不存在的图书。</p>
                <hr>
                
                <!-- 测试卡片 -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="card mb-4">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">图书ID查询测试</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label for="bookIdInput" class="form-label">图书ID</label>
                                    <input type="number" class="form-control" id="bookIdInput" value="1" min="1">
                                    <div class="form-text">输入1-10的ID查询存在的图书，输入其他ID测试不存在的图书</div>
                                </div>
                                
                                <div class="d-flex">
                                    <button id="getBookBtn" class="btn btn-info me-2">查询图书</button>
                                    <button id="testNotExistBtn" class="btn btn-warning">测试查询不存在图书</button>
                                </div>
                                <div class="mt-3">
                                    <div class="d-flex align-items-center">
                                        <span>查询状态：</span>
                                        <span id="getBookStatus" class="ms-2 badge bg-secondary">未查询</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 结果展示 -->
                <div class="card mb-4">
                    <div class="card-header bg-dark text-white">
                        <h5 class="mb-0">调用结果</h5>
                    </div>
                    <div class="card-body">
                        <ul class="nav nav-tabs" id="resultTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="service-tab" data-bs-toggle="tab" data-bs-target="#service" type="button" role="tab">服务信息</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="result-tab" data-bs-toggle="tab" data-bs-target="#result" type="button" role="tab">调用结果</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="book-tab" data-bs-toggle="tab" data-bs-target="#book" type="button" role="tab">图书详情</button>
                            </li>
                        </ul>
                        <div class="tab-content p-3 border border-top-0 rounded-bottom">
                            <div class="tab-pane fade show active" id="service" role="tabpanel">
                                <h6>当前服务信息：</h6>
                                <pre id="currentServiceInfo" class="bg-light p-3 rounded">未获取</pre>
                            </div>
                            <div class="tab-pane fade" id="result" role="tabpanel">
                                <h6>OpenFeign调用结果：</h6>
                                <pre id="feignResult" class="bg-light p-3 rounded">未调用</pre>
                            </div>
                            <div class="tab-pane fade" id="book" role="tabpanel">
                                <h6>图书详细信息：</h6>
                                <div id="bookDetails" class="bg-light p-3 rounded">
                                    <p class="text-muted">未查询图书</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 调用历史 -->
                <div class="card mb-4">
                    <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">调用历史</h5>
                        <button id="clearHistoryBtn" class="btn btn-sm btn-light">清空历史</button>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>时间</th>
                                        <th>类型</th>
                                        <th>参数</th>
                                        <th>端口</th>
                                        <th>状态</th>
                                        <th>结果</th>
                                    </tr>
                                </thead>
                                <tbody id="historyTableBody">
                                    <!-- 历史记录将通过JavaScript添加 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- 错误处理演示 -->
                <div class="card mb-4">
                    <div class="card-header bg-danger text-white">
                        <h5 class="mb-0">错误处理演示</h5>
                    </div>
                    <div class="card-body">
                        <p>本节演示OpenFeign服务调用中的错误处理情况，点击按钮测试不存在图书的场景：</p>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <div class="card h-100">
                                    <div class="card-body">
                                        <h5 class="card-title">不存在的图书</h5>
                                        <p class="card-text">测试查询不存在的图书ID (9999)，服务应返回正确的错误信息。</p>
                                        <button id="testNotExistBookBtn" class="btn btn-outline-danger">测试不存在图书</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 技术说明 -->
                <div class="card mb-4">
                    <div class="card-header bg-secondary text-white">
                        <h5 class="mb-0">OpenFeign技术说明</h5>
                    </div>
                    <div class="card-body">
                        <p>OpenFeign是Spring Cloud提供的声明式REST客户端，它使微服务之间的调用变得简单。主要特点：</p>
                        <ul>
                            <li>声明式REST调用，只需创建接口并使用注解配置</li>
                            <li>集成了负载均衡器，支持客户端负载均衡</li>
                            <li>与服务发现无缝集成，支持Consul、Eureka等注册中心</li>
                            <li>支持请求压缩和响应压缩</li>
                            <li>集成了断路器，提高系统的容错性</li>
                            <li>支持重试机制，处理网络抖动问题</li>
                        </ul>
                        <p>本测试页面实现了以下功能：</p>
                        <ul>
                            <li>基于ID查询图书 - 测试单一对象返回</li>
                            <li>测试查询不存在的图书 - 验证错误处理机制</li>
                            <li>记录测试历史 - 方便比较不同测试结果</li>
                        </ul>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <!-- 页脚 -->
    <footer th:replace="~{fragments/layout :: footer}"></footer>
    
    <!-- 脚本 -->
    <div th:replace="~{fragments/layout :: scripts}"></div>
    
    <!-- OpenFeign测试脚本 -->
    <script th:inline="javascript">
        document.addEventListener('DOMContentLoaded', function() {
            // 计数器
            let callCount = 0;
            
            // 获取DOM元素 - 查询图书
            const bookIdInput = document.getElementById('bookIdInput');
            const getBookBtn = document.getElementById('getBookBtn');
            const testNotExistBtn = document.getElementById('testNotExistBtn');
            const getBookStatus = document.getElementById('getBookStatus');
            
            // 获取DOM元素 - 错误测试
            const testNotExistBookBtn = document.getElementById('testNotExistBookBtn');
            
            // 获取DOM元素 - 结果展示
            const currentServiceInfoEl = document.getElementById('currentServiceInfo');
            const feignResultEl = document.getElementById('feignResult');
            const bookDetailsEl = document.getElementById('bookDetails');
            const historyTableBody = document.getElementById('historyTableBody');
            const clearHistoryBtn = document.getElementById('clearHistoryBtn');
            
            // 事件监听器
            getBookBtn.addEventListener('click', getBookById);
            testNotExistBtn.addEventListener('click', testNotExistBook);
            testNotExistBookBtn.addEventListener('click', testNotExistBook);
            clearHistoryBtn.addEventListener('click', clearHistory);
            
            // 根据ID查询图书
            function getBookById() {
                getBookStatus.textContent = '查询中...';
                getBookStatus.className = 'ms-2 badge bg-warning';
                
                // 获取图书ID
                const bookId = bookIdInput.value || 1;
                
                // 记录当前时间
                const startTime = new Date();
                
                // 发起请求
                fetch(`/api/feign-test/book?id=${bookId}`)
                    .then(response => response.json())
                    .then(data => {
                        // 更新调用状态
                        if (data.status === 'success') {
                            getBookStatus.textContent = '查询成功';
                            getBookStatus.className = 'ms-2 badge bg-success';
                            
                            // 显示图书详情
                            if (data.book) {
                                const book = data.book;
                                bookDetailsEl.innerHTML = `
                                    <div class="book-card">
                                        <h4>${book.title}</h4>
                                        <div class="book-info">
                                            <p><strong>作者:</strong> ${book.author}</p>
                                            <p><strong>出版社:</strong> ${book.publisher}</p>
                                            <p><strong>出版年份:</strong> ${book.publicationYear}</p>
                                            <p><strong>ISBN:</strong> ${book.isbn}</p>
                                            <p><strong>分类:</strong> ${book.category}</p>
                                            <p><strong>描述:</strong> ${book.description}</p>
                                            <p><strong>库存数量:</strong> ${book.quantity}</p>
                                            <p><strong>可借数量:</strong> ${book.availableQuantity}</p>
                                        </div>
                                    </div>
                                `;
                                
                                // 添加到历史记录
                                addToHistory({
                                    time: startTime,
                                    type: 'ID查询',
                                    param: bookId,
                                    port: data.currentPort,
                                    status: 'success',
                                    result: `《${book.title}》`
                                });
                            }
                        } else if (data.status === 'not_found') {
                            getBookStatus.textContent = '图书不存在';
                            getBookStatus.className = 'ms-2 badge bg-warning';
                            
                            // 显示错误信息
                            bookDetailsEl.innerHTML = `
                                <div class="alert alert-warning">
                                    <h5>图书不存在</h5>
                                    <p>ID: ${bookId} 的图书不存在或已被删除</p>
                                </div>
                            `;
                            
                            // 添加到历史记录
                            addToHistory({
                                time: startTime,
                                type: 'ID查询',
                                param: bookId,
                                port: data.currentPort,
                                status: 'not_found',
                                result: '图书不存在'
                            });
                        } else {
                            getBookStatus.textContent = '查询失败';
                            getBookStatus.className = 'ms-2 badge bg-danger';
                            
                            // 显示错误信息
                            const errorMsg = data.book && data.book.error ? data.book.error : '未知错误';
                            bookDetailsEl.innerHTML = `
                                <div class="alert alert-danger">
                                    <h5>查询失败</h5>
                                    <p>${errorMsg}</p>
                                </div>
                            `;
                            
                            // 添加到历史记录
                            addToHistory({
                                time: startTime,
                                type: 'ID查询',
                                param: bookId,
                                port: data.currentPort,
                                status: 'error',
                                result: errorMsg
                            });
                        }
                        
                        // 更新服务信息
                        currentServiceInfoEl.textContent = JSON.stringify({
                            currentPort: data.currentPort,
                            message: data.message
                        }, null, 2);
                        
                        // 更新调用结果
                        feignResultEl.textContent = JSON.stringify(data, null, 2);
                    })
                    .catch(error => {
                        getBookStatus.textContent = '查询错误';
                        getBookStatus.className = 'ms-2 badge bg-danger';
                        
                        // 显示错误信息
                        bookDetailsEl.innerHTML = `
                            <div class="alert alert-danger">
                                <h5>网络错误</h5>
                                <p>${error.message}</p>
                            </div>
                        `;
                        
                        // 添加到历史记录
                        addToHistory({
                            time: startTime,
                            type: 'ID查询',
                            param: bookId,
                            port: '-',
                            status: 'error',
                            result: error.message
                        });
                    });
            }
            
            // 测试查询不存在的图书
            function testNotExistBook() {
                getBookStatus.textContent = '测试中...';
                getBookStatus.className = 'ms-2 badge bg-info';
                
                // 记录当前时间
                const startTime = new Date();
                
                // 发起请求
                fetch('/api/feign-test/test-not-exist')
                    .then(response => response.json())
                    .then(data => {
                        // 更新调用状态
                        if (data.status === 'error') {
                            getBookStatus.textContent = '预期错误';
                            getBookStatus.className = 'ms-2 badge bg-success';
                        } else if (data.status === 'not_found') {
                            getBookStatus.textContent = '图书不存在';
                            getBookStatus.className = 'ms-2 badge bg-warning';
                        } else {
                            getBookStatus.textContent = '意外结果';
                            getBookStatus.className = 'ms-2 badge bg-danger';
                        }
                        
                        // 更新服务信息
                        currentServiceInfoEl.textContent = JSON.stringify({
                            currentPort: data.currentPort,
                            message: data.message,
                            testCase: data.testCase
                        }, null, 2);
                        
                        // 更新调用结果
                        feignResultEl.textContent = JSON.stringify(data, null, 2);
                        
                        // 显示图书详情
                        const errorMsg = data.book && data.book.error ? data.book.error : '未知错误';
                        bookDetailsEl.innerHTML = `
                            <div class="alert alert-${data.status === 'error' || data.status === 'not_found' ? 'success' : 'warning'}">
                                <h5>测试结果: ${data.status}</h5>
                                <p>测试案例: ${data.testCase}</p>
                                <p>错误信息: ${errorMsg}</p>
                            </div>
                        `;
                        
                        // 添加到历史记录
                        addToHistory({
                            time: startTime,
                            type: '不存在图书测试',
                            param: '9999',
                            port: data.currentPort,
                            status: data.status,
                            result: errorMsg
                        });
                    })
                    .catch(error => {
                        getBookStatus.textContent = '测试错误';
                        getBookStatus.className = 'ms-2 badge bg-danger';
                        
                        // 显示错误信息
                        bookDetailsEl.innerHTML = `
                            <div class="alert alert-danger">
                                <h5>网络错误</h5>
                                <p>${error.message}</p>
                            </div>
                        `;
                        
                        // 添加到历史记录
                        addToHistory({
                            time: startTime,
                            type: '不存在图书测试',
                            param: '9999',
                            port: '-',
                            status: 'error',
                            result: error.message
                        });
                    });
            }
            
            // 添加到历史记录
            function addToHistory(data) {
                callCount++;
                
                // 创建新行
                const newRow = document.createElement('tr');
                
                // 格式化时间
                const timeStr = data.time.toLocaleTimeString();
                
                // 设置状态样式
                let statusBadge = '';
                switch(data.status) {
                    case 'success':
                        statusBadge = '<span class="badge bg-success">成功</span>';
                        break;
                    case 'not_found':
                        statusBadge = '<span class="badge bg-warning">不存在</span>';
                        break;
                    case 'error':
                        statusBadge = '<span class="badge bg-danger">错误</span>';
                        break;
                    default:
                        statusBadge = `<span class="badge bg-secondary">${data.status}</span>`;
                }
                
                // 设置行内容
                newRow.innerHTML = `
                    <td>${callCount}</td>
                    <td>${timeStr}</td>
                    <td>${data.type}</td>
                    <td>${data.param}</td>
                    <td>${data.port}</td>
                    <td>${statusBadge}</td>
                    <td>${data.result}</td>
                `;
                
                // 添加到表格
                historyTableBody.insertBefore(newRow, historyTableBody.firstChild);
            }
            
            // 清空历史记录
            function clearHistory() {
                historyTableBody.innerHTML = '';
                callCount = 0;
            }
            
            // 初始加载时执行一次图书查询
            getBookById();
        });
    </script>
    
    <style>
        .book-card {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
        }
        .book-info p {
            margin-bottom: 0.5rem;
        }
        pre {
            max-height: 300px;
            overflow-y: auto;
        }
    </style>
</body>
</html> 